package com.njtoyo.taxi.admin.service.open.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.njtoyo.taxi.admin.logic.business.PrivacyNumberLogic;
import com.njtoyo.taxi.admin.mapper.master.entity.CallRelevance;
import com.njtoyo.taxi.admin.mapper.master.entity.DialRecord;
import com.njtoyo.taxi.admin.mapper.master.mapper.CallRelevanceMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.DialRecordMapper;
import com.njtoyo.taxi.admin.rest.wrapper.open.privacy_number.FeeWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.open.privacy_number.FinishWrapper;
import com.njtoyo.taxi.admin.service.open.PrivacyNumberService;
import com.taxi.entity.common.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

@Slf4j
@Service
public class PrivacyNumberServiceImpl implements PrivacyNumberService {
    
    @Autowired
    private CallRelevanceMapper callRelevanceMapper;
    
    @Autowired
    private DialRecordMapper dialRecordMapper;
    
    @Autowired
    private PrivacyNumberLogic privacyNumberLogic;
    
    @Override
    public RestResult feeNotify(FinishWrapper wrapper) {
        if (wrapper.getRecordUrl() == null || wrapper.getRecordUrl().isEmpty()) {
            return RestResult.failed("无通话记录");
        }
        QueryWrapper<CallRelevance> queryWrapper = new QueryWrapper<CallRelevance>().eq("subscription_id", wrapper.getSubid());
        CallRelevance callRelevance = callRelevanceMapper.selectOne(queryWrapper);
        if (Objects.isNull(callRelevance)) {
            log.info("未找到该绑定关系 {}", wrapper);
            return RestResult.success();
        }
        // 判断是否已记录
        if (Objects.nonNull(wrapper.getRequestId())) {
            DialRecord dial = dialRecordMapper.selectOne((new QueryWrapper<DialRecord>()).eq("icid", wrapper.getRequestId()));
            if (Objects.nonNull(dial)) {
                log.info("该通话记录已保存 {}", dial);
                return RestResult.success();
            }
        }
        DialRecord record = new DialRecord();
        record.setCallRelevanceId(callRelevance.getId())
                .setIcid(wrapper.getRequestId())
                .setCreatedAt(new Date())
                .setUpdatedAt(new Date())
                .setHuaweiUrl(wrapper.getRecordUrl())
                .setDetail(wrapper);
        dialRecordMapper.insert(record);
        // 当通话有录音的时候，启动异步任务,保存录音文件
        if (Objects.nonNull(wrapper.getRecordUrl())) {
            privacyNumberLogic.downloadFileSave(record);
        }
        return RestResult.success();
    }
}
